package org.jeecg.modules.bobo.wechat.miniapp.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaTemplateData;
import cn.binarywang.wx.miniapp.bean.WxMaUniformMessage;
import cn.binarywang.wx.miniapp.bean.template.*;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.jeecg.modules.bobo.common.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 微信小程序模版推送实现
 * @program: jeecg-boot-parent
 * @description:
 * @author: 三千霜
 * @create: 2020-07-20 15:29
 */
@RestController
@RequestMapping("/api/wx/miniapp/PushMsg")
@Api(tags = "微信模块小程序api")
@Slf4j
@ApiSort(value = 3)
public class WxMaPushMessageController {
    @Autowired
    private WxMaService wxMaService;

    @GetMapping("/push")
    @ApiOperation("模板消息推送接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openid",value = "openid"),
            @ApiImplicitParam(name = "用户的formid",value = "formid")
    })
    public Result<String> push(@RequestParam String openid, @RequestParam String formid) {

        //2,设置模版信息（keyword1：类型，keyword2：内容）
        List<WxMaTemplateData> templateDataList = new ArrayList<>(2);
        WxMaTemplateData data1 = new WxMaTemplateData("keyword1", "获取老师微信");
        WxMaTemplateData data2 = new WxMaTemplateData("keyword2", "2501902696");
        templateDataList.add(data1);
        templateDataList.add(data2);

        //3，设置推送消息
        WxMaUniformMessage templateMessage = WxMaUniformMessage.builder()
                .toUser(openid)//要推送的用户openid
                .formId(formid)//收集到的formid
                .templateId("eDZCu__qIz64Xx19dAoKg0Taf5AAoDmhUHprF6CAd4A")//推送的模版id（在小程序后台设置）
                .data(templateDataList)//模版信息
                .page("pages/index/index")//要跳转到小程序那个页面
                .build();
        //4，发起推送
        try {
            wxMaService.getMsgService().sendUniformMsg(templateMessage);
        } catch (WxErrorException e) {
            System.out.println("推送失败：" + e.getMessage());
            return Result.error(e.getMessage());
        }
        return Result.success("推送成功");
    }
}
